package dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class BaseDao {
    private static String driver = "com.mysql.jdbc.Driver";
    private static String user = "root";
    private static String passworld = "admin";
    private static String url = "jdbc:mysql://localhost:3306/insure?useUnicode=true&characterEncoding=utf8";

    private Connection connection = null;
    private PreparedStatement pstmt = null;

    //获取连接
    private Connection getConnection(){
        try {
            Class.forName(driver);
            System.out.println("驱动已加载");
            connection = DriverManager.getConnection(url,user,passworld);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //查询方法
    public ResultSet executeQuerySql(String sql,Object[] obj){
        connection = getConnection();
        try {
            pstmt = connection.prepareStatement(sql);
            if (pstmt != null){
                for (int i = 0;i<obj.length;i++){
                    pstmt.setObject(i+1,obj[i]);
                }
            }
            return pstmt.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;
    }

    //增删改查方法
    public int executeUpdateSql(String sql,Object[] obj){
        connection = getConnection();
        try {
            pstmt = connection.prepareStatement(sql);
            if (pstmt != null && obj != null){
                for (int i=0;i<obj.length;i++){
                    pstmt.setObject(i+1,obj[i]);
                }

                return pstmt.executeUpdate();
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return 0;
    }

    public void close(){
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            System.out.println("连接已关闭");
        }
    }

    //测试
    public static void main(String[] args) {
        String sql = "SELECT * FROM user WHERE u_name = ?;";
        Scanner sc = new Scanner(System.in);
        String name = sc.next();
        Object[] obj = {name};

        BaseDao baseDao = new BaseDao();
        ResultSet rs = baseDao.executeQuerySql(sql,obj);

        try {
            while (rs.next()){
                System.out.println(rs.getString(1));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        baseDao.close();
    }
}
